
const util = require('./../utils/util');
import { connectPage } from 'mobx-miniprogram-lite'
import {  userStore as uStore } from './../stores/userStore'

connectPage({
  store: { "userStore": uStore },
  data: {
    showPrivacy:false,
    reg: {
      regtype: 'hotel'
    },
    reg1companySN: '',
    reg1companyName: '',
    reg1realName: '',
    reg1roleIds: 2,
    reg1mobileNo: '',
    
    userInfo: {
      avatarUrl: 'https://tse2-mm.cn.bing.net/th/id/OIP-C.DUOb0xKtw4cXQPnkOxlKCgAAAA?rs=1&pid=ImgDetMain',
      nickName: 'mockname',
      roleName: '酒店经理'
    }
  },
  handleAgreePrivacyAuthorization() {
    // 用户点击同意按钮后
    this.resolvePrivacyAuthorization({ buttonId: 'agree-btn', event: 'agree' })
  },
  onLoad() {
    //TODO是否要有获取手机号码的接口 待定
    wx.onNeedPrivacyAuthorization(resolve => {
      // 需要用户同意隐私授权时
      // 弹出开发者自定义的隐私授权弹窗
      this.setData({
        showPrivacy: true
      })
      this.resolvePrivacyAuthorization = resolve
    });

    wx.requirePrivacyAuthorize({
      success: () => {
        // 用户同意授权
        // 继续小程序逻辑
      },
      fail: () => {}, // 用户拒绝授权
      complete: () => {}
    })
 

    this.login((res: any) => {
      // 登录code获取openid,用回调保存到userStore中.
      console.log(res.code)
      console.log('first request code get openid ')

      this.store.userStore.setUserInfo(res.data.data)
      wx.setStorageSync('openid', res.data.data.wxOpenid)
      console.log('save openid to storage sync.')

    })
  },

  onShow() {

    console.log('onShow')
  },
  onHide() {
    console.log('onHide')
  },
  onUnload() {
    console.log('onUnload')
  },
  regTypeChange(event: any) {
    console.log(event)
    if (event.target.dataset.regtype != null) {
      this.setData({
        "reg": {
          regtype: event.target.dataset.regtype
        }
      })
    }
  },
  submitReg(){
    var param = this.validRegInfo();
    if(Object.keys(param).length>0) {
      param['wxOpenid'] = this.store.userStore.userInfo.wxOpenid;
      util.request_json_post("/api/wechat/regCompany",param).then((res)=>{
          if(res.data.code==200) {
            wx.showToast({title:'注册成功'})
            this.store.userStore.setUserInfo(res.data.data)
            wx.redirectTo({url:'/miniprogram/pages/appversion.wxml'})
          } else{
            wx.showToast({title:'后台服务器忙,请稍后在试'});
          }

      })
    }
  },
  validRegInfo() {
    var param = {};
    for (var key in this.data) {
      if(key.startsWith('reg1')) {
        if(''==this.data[key] || null==this.data[key]) {
          console.log(key)
          wx.showToast({title:'填写不完整',icon:'error',duration:1000})        
          return false;
         } else {
          param[key.replace('reg1','')] = this.data[key];
         }
      }   
    }
    
    return param;
  
  },

  getPhoneMumber(e:Event) {
    console.log(e);
    var codeOfgetPhone = e.detail.code;
    request_post("/api/wechat/bindPhoneNumber",{"phoneCode":codeOfgetPhone}).then((res=>{
        userStore.setUserInfo(res.data.data);
    }))
  },

  login(callback: any) {

    wx.login({
      success(res: any) {
        console.log(res)
        if (res.code) {
          // 发起网络请求
          wx.request({
            url: 'http://qq308745107.xicp.net/api/wechat/callback',
            dataType: 'json',
            method: 'GET',
            data: {
              code: res.code
            },
            success: callback
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },

  getUserProfile() {
    var openid = wx.getStorageSync('openid')

    if (openid == '') {
      var openid = this.store.userStore.userInfo.wxOpenid
    }
    console.log('openidout', openid)

    wx.getUserProfile({
      desc: '用于完善会员资料' // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
    }).then((res) => {
      const wxOpenid = this.store.userStore.userInfo.wxOpenid
      console.log('wxOpenid', wxOpenid)
      console.log('openid', openid)
      wx.request({
        url: 'http://bi889yu555.vicp.fun/api/wechat/updateUserInfo',
        data: {
          wxOpenId: openid,
          encryptedData: res.encryptedData,
          iv: res.iv
        },
        dataType: 'json',
        method: 'POST',
        success: (res) => {
          console.log(res.data.data.wxOpenid)

          // 判断是否授权成功
          if (res.data.code === 200) {
            // 将用户的openid缓存起来
            wx.setStorageSync('selfinfo', res.data.data);
            this.store.userStore.setUserInfo(res.data.data)
          } else {
            console.log('request server erorr.')
          }
        }
      })
    })
  }
})